package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.dto.ConstructionWarningQueryDTO;
import com.ruoyi.system.entity.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IConstructionWarningService;
import com.ruoyi.system.vo.ConstructionWarningOverviewVO;
import com.ruoyi.system.vo.ConstructionWarningVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 施工预警服务实现类
 * 
 * @author ruoyi
 * @since 2024-01-01
 */
@Service
@Slf4j
public class ConstructionWarningServiceImpl implements IConstructionWarningService {

    @Resource
    private ConstructionWarningConfigMapper configMapper;

    @Resource
    private ConstructionItemMapper constructionItemMapper;

    @Resource
    private ConstructionProjectMapper constructionProjectMapper;

    @Resource
    private AcceptanceChecklistInstanceMapper acceptanceInstanceMapper;

    @Resource
    private AcceptanceChecklistRecordMapper acceptanceRecordMapper;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public ConstructionWarningOverviewVO getWarningOverview(ConstructionWarningQueryDTO queryDTO) {
        ConstructionWarningOverviewVO overview = new ConstructionWarningOverviewVO();

        // 1. 获取预警统计卡片
        List<ConstructionWarningOverviewVO.WarningStatisticsCardVO> statisticsCards = getWarningStatistics();
        overview.setStatisticsCards(statisticsCards);

        // 2. 获取预警趋势数据
        String trendWarningType = queryDTO != null ? queryDTO.getWarningType() : null;
        List<ConstructionWarningOverviewVO.WarningTrendDataVO> trendData = getWarningTrendData(trendWarningType);
        overview.setTrendData(trendData);

        // 3. 获取预警项目列表
        List<ConstructionWarningVO> warningList = getWarningList(queryDTO);
        overview.setWarningList(warningList);

        return overview;
    }

    @Override
    public List<ConstructionWarningVO> getWarningList(ConstructionWarningQueryDTO queryDTO) {
        List<ConstructionWarningVO> allWarnings = new ArrayList<>();
        
        // 1. 查询进度预警
        List<ConstructionWarningVO> progressWarnings = getProgressWarnings(queryDTO);
        allWarnings.addAll(progressWarnings);
        
        // 2. 查询质量预警
        List<ConstructionWarningVO> qualityWarnings = getQualityWarnings(queryDTO);
        allWarnings.addAll(qualityWarnings);
        
        // 3. 按预警等级和时间排序
        allWarnings.sort((w1, w2) -> {
            // 先按预警等级排序（高危→中危→低危）
            int levelCompare = getWarningLevelOrder(w2.getWarningLevel()) - getWarningLevelOrder(w1.getWarningLevel());
            if (levelCompare != 0) {
                return levelCompare;
            }
            // 再按触发时间排序（最新在前）
            return w2.getTriggerTime().compareTo(w1.getTriggerTime());
        });
        
        return allWarnings;
    }

    @Override
    public ConstructionWarningVO getWarningDetail(Long projectId, String warningType, Long businessId) {
        // 实时查询预警详情
        if ("progress".equals(warningType)) {
            return getProgressWarningDetail(projectId, businessId);
        } else if ("quality".equals(warningType)) {
            return getQualityWarningDetail(projectId, businessId);
        } else {
            throw new ServiceException("不支持的预警类型: " + warningType);
        }
    }

    @Override
    public List<ConstructionWarningOverviewVO.WarningStatisticsCardVO> getWarningStatistics() {
        List<ConstructionWarningOverviewVO.WarningStatisticsCardVO> cards = new ArrayList<>();

        // 1. 进度预警统计
        ConstructionWarningOverviewVO.WarningStatisticsCardVO progressCard = new ConstructionWarningOverviewVO.WarningStatisticsCardVO();
        progressCard.setWarningType("progress");
        progressCard.setWarningTypeName("进度预警");
        progressCard.setWarningLevel("all");
        progressCard.setWarningLevelName("全部");
        progressCard.setWarningCount(getProgressWarningCount());
        progressCard.setHandledCount(getProgressHandledCount());
        progressCard.setHandleRate(calculateHandleRate(progressCard.getWarningCount(), progressCard.getHandledCount()));
        progressCard.setCardColor("#fa8c16"); // 橙色
        cards.add(progressCard);

        // 2. 质量预警统计
        ConstructionWarningOverviewVO.WarningStatisticsCardVO qualityCard = new ConstructionWarningOverviewVO.WarningStatisticsCardVO();
        qualityCard.setWarningType("quality");
        qualityCard.setWarningTypeName("验收质量预警");
        qualityCard.setWarningLevel("all");
        qualityCard.setWarningLevelName("全部");
        qualityCard.setWarningCount(getQualityWarningCount());
        qualityCard.setHandledCount(getQualityHandledCount());
        qualityCard.setHandleRate(calculateHandleRate(qualityCard.getWarningCount(), qualityCard.getHandledCount()));
        qualityCard.setCardColor("#fadb14"); // 黄色
        cards.add(qualityCard);

        return cards;
    }

    @Override
    public List<ConstructionWarningOverviewVO.WarningTrendDataVO> getWarningTrendData(String warningType) {
        // 计算近30天的日期范围
        LocalDateTime endDate = LocalDateTime.now();
        LocalDateTime startDate = endDate.minusDays(30);

        // 实时查询趋势数据
        List<ConstructionWarningOverviewVO.WarningTrendDataVO> trendData = new ArrayList<>();
        
        // 按天统计预警数量
        for (int i = 0; i < 30; i++) {
            LocalDateTime currentDate = startDate.plusDays(i);
            LocalDateTime nextDate = currentDate.plusDays(1);
            
            ConstructionWarningOverviewVO.WarningTrendDataVO trendItem = new ConstructionWarningOverviewVO.WarningTrendDataVO();
            trendItem.setDate(currentDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            
            int count = 0;
            if (warningType == null || "progress".equals(warningType)) {
                count += getProgressWarningCountByDateRange(currentDate, nextDate);
            }
            if (warningType == null || "quality".equals(warningType)) {
                count += getQualityWarningCountByDateRange(currentDate, nextDate);
            }
            
            trendItem.setNewWarningCount(count);
            trendItem.setWarningType(warningType);
            trendItem.setWarningTypeName(getWarningTypeName(warningType));
            
            trendData.add(trendItem);
        }
        
        return trendData;
    }

    @Override
    public List<Object> getWarningTypeOptions() {
        List<Object> options = new ArrayList<>();
        
        Map<String, String> option1 = new HashMap<>();
        option1.put("value", "progress");
        option1.put("label", "进度预警");
        options.add(option1);
        
        Map<String, String> option2 = new HashMap<>();
        option2.put("value", "quality");
        option2.put("label", "质量预警");
        options.add(option2);
        
        return options;
    }

    @Override
    public List<Object> getWarningLevelOptions() {
        List<Object> options = new ArrayList<>();
        
        Map<String, String> option1 = new HashMap<>();
        option1.put("value", "high");
        option1.put("label", "高危");
        options.add(option1);
        
        Map<String, String> option2 = new HashMap<>();
        option2.put("value", "medium");
        option2.put("label", "中危");
        options.add(option2);
        
        Map<String, String> option3 = new HashMap<>();
        option3.put("value", "low");
        option3.put("label", "低危");
        options.add(option3);
        
        return options;
    }

    @Override
    public List<Object> getStatusOptions() {
        List<Object> options = new ArrayList<>();
        
        Map<String, Object> option1 = new HashMap<>();
        option1.put("value", 0);
        option1.put("label", "未处理");
        options.add(option1);
        
        Map<String, Object> option2 = new HashMap<>();
        option2.put("value", 1);
        option2.put("label", "处理中");
        options.add(option2);
        
        Map<String, Object> option3 = new HashMap<>();
        option3.put("value", 2);
        option3.put("label", "已完成");
        options.add(option3);
        
        return options;
    }

    /**
     * 获取进度预警列表
     */
    private List<ConstructionWarningVO> getProgressWarnings(ConstructionWarningQueryDTO queryDTO) {
        List<ConstructionWarningVO> warnings = new ArrayList<>();
        
        // 1. 查询所有施工项目
        LambdaQueryWrapper<ConstructionProjectDO> projectWrapper = new LambdaQueryWrapper<>();
        projectWrapper.eq(ConstructionProjectDO::getIsDeleted, 0);
        if (queryDTO != null && queryDTO.getProjectId() != null) {
            projectWrapper.eq(ConstructionProjectDO::getId, queryDTO.getProjectId());
        }
        if (queryDTO != null && StringUtils.isNotEmpty(queryDTO.getProjectCode())) {
            projectWrapper.like(ConstructionProjectDO::getProjectCode, queryDTO.getProjectCode());
        }
        if (queryDTO != null && StringUtils.isNotEmpty(queryDTO.getProjectName())) {
            projectWrapper.like(ConstructionProjectDO::getProjectName, queryDTO.getProjectName());
        }
        
        List<ConstructionProjectDO> projects = constructionProjectMapper.selectList(projectWrapper);
        
        // 2. 遍历每个项目，检查施工事项进度
        for (ConstructionProjectDO project : projects) {
            // 查询项目下的所有施工事项
            LambdaQueryWrapper<ConstructionProjectItemDO> itemWrapper = new LambdaQueryWrapper<>();
            itemWrapper.eq(ConstructionProjectItemDO::getProjectId, project.getId())
                      .eq(ConstructionProjectItemDO::getIsDeleted, 0)
                      .in(ConstructionProjectItemDO::getCompletionStatus, Arrays.asList(0, 1)); // 未开始或进行中
            
            List<ConstructionProjectItemDO> items = constructionItemMapper.selectList(itemWrapper);
            
            // 3. 检查每个施工事项的进度延误情况
            for (ConstructionProjectItemDO item : items) {
                ConstructionWarningVO warning = checkProgressDelay(project, item);
                if (warning != null) {
                    // 应用查询条件过滤
                    if (isWarningMatchQuery(warning, queryDTO)) {
                        warnings.add(warning);
                    }
                }
            }
        }
        
        return warnings;
    }

    /**
     * 检查施工事项进度延误
     */
    private ConstructionWarningVO checkProgressDelay(ConstructionProjectDO project, ConstructionProjectItemDO item) {
        LocalDate today = LocalDate.now();
        LocalDate plannedEndDate = item.getEndTime();
        
        // 如果计划结束时间已过且事项未完成，则产生预警
        if (plannedEndDate != null && today.isAfter(plannedEndDate) && item.getCompletionStatus() != 2) {
            long delayDays = ChronoUnit.DAYS.between(plannedEndDate, today);
            
            // 根据延误天数判断预警等级
            String warningLevel = getProgressWarningLevel(delayDays);
            if (warningLevel != null) {
                ConstructionWarningVO warning = new ConstructionWarningVO();
                warning.setProjectId(project.getId());
                warning.setProjectCode(project.getProjectCode());
                warning.setProjectName(project.getProjectName());
                warning.setProjectStage(project.getCurrentStageName());
                warning.setProjectStageName(project.getCurrentStageName());
                warning.setWarningType("progress");
                warning.setWarningTypeName("进度预警");
                warning.setWarningLevel(warningLevel);
                warning.setWarningLevelName(getWarningLevelName(warningLevel));
                warning.setWarningTitle("施工进度延误预警");
                warning.setWarningDesc(String.format("施工事项【%s】比计划延误%d天，当前状态：%s", 
                    item.getItemName(), delayDays, getItemStatusName(item.getCompletionStatus())));
                warning.setBusinessId(item.getId());
                warning.setBusinessName(item.getItemName());
                warning.setTriggerTime(LocalDateTime.now());
                
                // 设置预警详情数据
                Map<String, Object> warningData = new HashMap<>();
                warningData.put("itemId", item.getId());
                warningData.put("itemName", item.getItemName());
                warningData.put("plannedStartDate", item.getStartTime());
                warningData.put("plannedEndDate", item.getEndTime());
                warningData.put("actualStatus", item.getCompletionStatus());
                warningData.put("delayDays", delayDays);
                warningData.put("durationDays", item.getDurationDays());
                warning.setWarningData(warningData);
                
                return warning;
            }
        }
        
        return null;
    }

    /**
     * 根据延误天数获取进度预警等级
     */
    private String getProgressWarningLevel(long delayDays) {
        // 获取进度预警配置
        LambdaQueryWrapper<ConstructionWarningConfigDO> configWrapper = new LambdaQueryWrapper<>();
        configWrapper.eq(ConstructionWarningConfigDO::getWarningType, "progress")
                    .eq(ConstructionWarningConfigDO::getIsEnabled, true)
                    .eq(ConstructionWarningConfigDO::getIsDeleted, 0);
        
        List<ConstructionWarningConfigDO> configs = configMapper.selectList(configWrapper);
        
        // 如果没有配置，使用默认规则
        if (configs.isEmpty()) {
            if (delayDays >= 7) return "high";
            if (delayDays >= 3) return "medium";
            if (delayDays >= 1) return "low";
            return null;
        }
        
        // 根据配置判断预警等级
        for (ConstructionWarningConfigDO config : configs) {
            try {
                // 解析触发条件
                Map<String, Object> condition = parseTriggerCondition(config.getTriggerCondition());
                if (condition != null) {
                    Integer threshold = (Integer) condition.get("delayDays");
                    if (threshold != null && delayDays >= threshold) {
                        return config.getWarningLevel();
                    }
                }
            } catch (Exception e) {
                log.warn("解析预警配置失败: {}", config.getTriggerCondition(), e);
            }
        }
        
        return null;
    }

    /**
     * 获取质量预警列表
     */
    private List<ConstructionWarningVO> getQualityWarnings(ConstructionWarningQueryDTO queryDTO) {
        List<ConstructionWarningVO> warnings = new ArrayList<>();
        
        // 1. 查询所有验收单实例
        LambdaQueryWrapper<AcceptanceChecklistInstanceDO> instanceWrapper = new LambdaQueryWrapper<>();
        instanceWrapper.eq(AcceptanceChecklistInstanceDO::getIsDeleted, 0)
                      .in(AcceptanceChecklistInstanceDO::getStatus, Arrays.asList("PENDING", "IN_PROGRESS", "COMPLETED"));
        
        if (queryDTO != null && queryDTO.getProjectId() != null) {
            instanceWrapper.eq(AcceptanceChecklistInstanceDO::getProjectId, queryDTO.getProjectId());
        }
        
        List<AcceptanceChecklistInstanceDO> instances = acceptanceInstanceMapper.selectList(instanceWrapper);
        
        // 2. 遍历每个验收单实例，检查验收质量情况
        for (AcceptanceChecklistInstanceDO instance : instances) {
            ConstructionWarningVO warning = checkQualityIssue(instance);
            if (warning != null) {
                // 应用查询条件过滤
                if (isWarningMatchQuery(warning, queryDTO)) {
                    warnings.add(warning);
                }
            }
        }
        
        return warnings;
    }

    /**
     * 检查验收质量异常
     */
    private ConstructionWarningVO checkQualityIssue(AcceptanceChecklistInstanceDO instance) {
        // 查询验收单填写记录
        LambdaQueryWrapper<AcceptanceChecklistRecordDO> recordWrapper = new LambdaQueryWrapper<>();
        recordWrapper.eq(AcceptanceChecklistRecordDO::getInstanceId, instance.getId())
                    .eq(AcceptanceChecklistRecordDO::getIsDeleted, 0);
        
        List<AcceptanceChecklistRecordDO> records = acceptanceRecordMapper.selectList(recordWrapper);
        
        if (records.isEmpty()) {
            return null;
        }
        
        // 计算验收通过率
        long totalItems = records.size();
        long completedItems = records.stream().mapToLong(r -> r.getIsCompleted() != null ? r.getIsCompleted() : 0).sum();
        double completionRate = totalItems > 0 ? (double) completedItems / totalItems : 0.0;
        
        // 检查是否有质量问题
        long qualityIssues = records.stream()
                .filter(r -> r.getIsCompleted() != null && r.getIsCompleted() == 0)
                .count();
        
        // 根据验收通过率和质量问题数量判断预警等级
        String warningLevel = getQualityWarningLevel(completionRate, qualityIssues, totalItems);
        if (warningLevel != null) {
            ConstructionWarningVO warning = new ConstructionWarningVO();
            warning.setProjectId(instance.getProjectId());
            warning.setProjectCode("PROJ-" + instance.getProjectId()); // TODO: 从项目表获取
            warning.setProjectName("项目-" + instance.getProjectId()); // TODO: 从项目表获取
            warning.setProjectStage("验收阶段");
            warning.setProjectStageName("验收阶段");
            warning.setWarningType("quality");
            warning.setWarningTypeName("质量预警");
            warning.setWarningLevel(warningLevel);
            warning.setWarningLevelName(getWarningLevelName(warningLevel));
            warning.setWarningTitle("验收质量异常预警");
            warning.setWarningDesc(String.format("验收单【%s】存在质量问题，通过率：%.1f%%，未完成项：%d个", 
                instance.getInstanceName(), completionRate * 100, qualityIssues));
            warning.setBusinessId(instance.getId());
            warning.setBusinessName(instance.getInstanceName());
            warning.setTriggerTime(LocalDateTime.now());
            
            // 设置预警详情数据
            Map<String, Object> warningData = new HashMap<>();
            warningData.put("instanceId", instance.getId());
            warningData.put("instanceName", instance.getInstanceName());
            warningData.put("totalItems", totalItems);
            warningData.put("completedItems", completedItems);
            warningData.put("completionRate", completionRate);
            warningData.put("qualityIssues", qualityIssues);
            warningData.put("status", instance.getStatus());
            warning.setWarningData(warningData);
            
            return warning;
        }
        
        return null;
    }

    /**
     * 根据验收通过率和质量问题数量获取质量预警等级
     */
    private String getQualityWarningLevel(double completionRate, long qualityIssues, long totalItems) {
        // 获取质量预警配置
        LambdaQueryWrapper<ConstructionWarningConfigDO> configWrapper = new LambdaQueryWrapper<>();
        configWrapper.eq(ConstructionWarningConfigDO::getWarningType, "quality")
                    .eq(ConstructionWarningConfigDO::getIsEnabled, true)
                    .eq(ConstructionWarningConfigDO::getIsDeleted, 0);
        
        List<ConstructionWarningConfigDO> configs = configMapper.selectList(configWrapper);
        
        // 如果没有配置，使用默认规则
        if (configs.isEmpty()) {
            if (completionRate < 0.5 || qualityIssues >= 5) return "high";
            if (completionRate < 0.7 || qualityIssues >= 3) return "medium";
            if (completionRate < 0.9 || qualityIssues >= 1) return "low";
            return null;
        }
        
        // 根据配置判断预警等级
        for (ConstructionWarningConfigDO config : configs) {
            try {
                // 解析触发条件
                Map<String, Object> condition = parseTriggerCondition(config.getTriggerCondition());
                if (condition != null) {
                    Double minCompletionRate = (Double) condition.get("minCompletionRate");
                    Integer maxQualityIssues = (Integer) condition.get("maxQualityIssues");
                    
                    boolean triggerWarning = false;
                    if (minCompletionRate != null && completionRate < minCompletionRate) {
                        triggerWarning = true;
                    }
                    if (maxQualityIssues != null && qualityIssues >= maxQualityIssues) {
                        triggerWarning = true;
                    }
                    
                    if (triggerWarning) {
                        return config.getWarningLevel();
                    }
                }
            } catch (Exception e) {
                log.warn("解析预警配置失败: {}", config.getTriggerCondition(), e);
            }
        }
        
        return null;
    }

    /**
     * 获取进度预警数量
     */
    private Integer getProgressWarningCount() {
        List<ConstructionWarningVO> warnings = getProgressWarnings(null);
        return warnings.size();
    }

    /**
     * 获取进度预警已处理数量
     */
    private Integer getProgressHandledCount() {
        // 由于是实时查询，这里暂时返回0，实际应该根据业务逻辑判断是否已处理
        return 0;
    }

    /**
     * 获取质量预警数量
     */
    private Integer getQualityWarningCount() {
        List<ConstructionWarningVO> warnings = getQualityWarnings(null);
        return warnings.size();
    }

    /**
     * 获取质量预警已处理数量
     */
    private Integer getQualityHandledCount() {
        // 由于是实时查询，这里暂时返回0，实际应该根据业务逻辑判断是否已处理
        return 0;
    }

    /**
     * 获取指定日期范围的进度预警数量
     */
    private Integer getProgressWarningCountByDateRange(LocalDateTime startDate, LocalDateTime endDate) {
        // 实时统计指定日期范围的进度预警数量
        // 这里简化处理，实际应该根据触发时间范围过滤
        return getProgressWarningCount();
    }

    /**
     * 获取指定日期范围的质量预警数量
     */
    private Integer getQualityWarningCountByDateRange(LocalDateTime startDate, LocalDateTime endDate) {
        // 实时统计指定日期范围的质量预警数量
        // 这里简化处理，实际应该根据触发时间范围过滤
        return getQualityWarningCount();
    }

    /**
     * 获取进度预警详情
     */
    private ConstructionWarningVO getProgressWarningDetail(Long projectId, Long businessId) {
        // TODO: 实时查询施工进度详情
        // 查询施工计划表，获取具体的进度延误信息
        ConstructionWarningVO vo = new ConstructionWarningVO();
        vo.setProjectId(projectId);
        vo.setWarningType("progress");
        vo.setWarningTypeName("进度预警");
        vo.setBusinessId(businessId);
        vo.setBusinessName("施工项-" + businessId);
        return vo;
    }

    /**
     * 获取质量预警详情
     */
    private ConstructionWarningVO getQualityWarningDetail(Long projectId, Long businessId) {
        // TODO: 实时查询验收质量详情
        // 查询验收单表，获取具体的质量异常信息
        ConstructionWarningVO vo = new ConstructionWarningVO();
        vo.setProjectId(projectId);
        vo.setWarningType("quality");
        vo.setWarningTypeName("质量预警");
        vo.setBusinessId(businessId);
        vo.setBusinessName("验收单-" + businessId);
        return vo;
    }

    /**
     * 计算处理率
     */
    private String calculateHandleRate(Integer totalCount, Integer handledCount) {
        if (totalCount == null || totalCount == 0) {
            return "0%";
        }
        if (handledCount == null) {
            handledCount = 0;
        }
        double rate = (double) handledCount / totalCount * 100;
        return String.format("%.0f%%", rate);
    }

    /**
     * 获取预警等级排序值
     */
    private int getWarningLevelOrder(String warningLevel) {
        switch (warningLevel) {
            case "high":
                return 3;
            case "medium":
                return 2;
            case "low":
                return 1;
            default:
                return 0;
        }
    }

    /**
     * 获取预警类型名称
     */
    private String getWarningTypeName(String warningType) {
        switch (warningType) {
            case "progress":
                return "进度预警";
            case "quality":
                return "质量预警";
            default:
                return warningType;
        }
    }

    /**
     * 获取预警等级名称
     */
    private String getWarningLevelName(String warningLevel) {
        switch (warningLevel) {
            case "high":
                return "高危";
            case "medium":
                return "中危";
            case "low":
                return "低危";
            default:
                return warningLevel;
        }
    }

    /**
     * 获取施工事项状态名称
     */
    private String getItemStatusName(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 0:
                return "未开始";
            case 1:
                return "进行中";
            case 2:
                return "已完成";
            default:
                return "未知";
        }
    }

    /**
     * 解析触发条件JSON
     */
    private Map<String, Object> parseTriggerCondition(String triggerCondition) {
        if (StringUtils.isEmpty(triggerCondition)) {
            return null;
        }
        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> result = objectMapper.readValue(triggerCondition, Map.class);
            return result;
        } catch (Exception e) {
            log.warn("解析触发条件失败: {}", triggerCondition, e);
            return null;
        }
    }

    /**
     * 判断预警是否匹配查询条件
     */
    private boolean isWarningMatchQuery(ConstructionWarningVO warning, ConstructionWarningQueryDTO queryDTO) {
        if (queryDTO == null) {
            return true;
        }

        // 预警类型过滤
        if (StringUtils.isNotEmpty(queryDTO.getWarningType()) && 
            !queryDTO.getWarningType().equals(warning.getWarningType())) {
            return false;
        }
        if (queryDTO.getWarningTypes() != null && !queryDTO.getWarningTypes().isEmpty() &&
            !queryDTO.getWarningTypes().contains(warning.getWarningType())) {
            return false;
        }

        // 预警等级过滤
        if (StringUtils.isNotEmpty(queryDTO.getWarningLevel()) && 
            !queryDTO.getWarningLevel().equals(warning.getWarningLevel())) {
            return false;
        }
        if (queryDTO.getWarningLevels() != null && !queryDTO.getWarningLevels().isEmpty() &&
            !queryDTO.getWarningLevels().contains(warning.getWarningLevel())) {
            return false;
        }

        // 项目阶段过滤
        if (StringUtils.isNotEmpty(queryDTO.getProjectStage()) && 
            !queryDTO.getProjectStage().equals(warning.getProjectStage())) {
            return false;
        }

        return true;
    }

}
